//
//  CookieHelper.m
//  DemoForWK
//
//  Created by huchu on 2018/9/21.
//  Copyright © 2018年 Synjones. All rights reserved.
//

#import "CookieHelper.h"

@implementation CookieHelper


+ (NSMutableArray<NSString *> *)GetNSHTTPCookieStorageJavaScriptArray {
    NSMutableArray<NSString *> *cookieStrings = [[NSMutableArray alloc] init];
    //取出cookie
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in cookieStorage.cookies) {
        //
        NSString *excuteJSString = [NSString stringWithFormat:@"%@=%@;", cookie.name, cookie.value];
        if (cookie.domain.length > 0) {
            excuteJSString = [excuteJSString stringByAppendingFormat:@"domain=%@;", cookie.domain];
        }
        if (cookie.path.length > 0) {
            excuteJSString = [excuteJSString stringByAppendingFormat:@"path=%@;", cookie.path];
        }
        if (cookie.expiresDate != nil) {
            excuteJSString = [excuteJSString stringByAppendingFormat:@"expires=%@;", cookie.expiresDate];
        }
        if (cookie.secure) {
            excuteJSString = [excuteJSString stringByAppendingString:@"secure=true"];
        }
        
        [cookieStrings addObject:excuteJSString];
        //DDLogDebug(@"[JSBridge] cookie to be set = %@", excuteJSString);
    }
    // 检查cookie的数量，正常的应该是 7 个
    //DDLogInfo(@"[JSBridge] cookieJavaScriptArray. cookie.length = %ld", cookieStrings.count);
    //执行js
    return cookieStrings;
}


//给指定的url设置cookies

+(void)addCookieToURL:(NSURL *)url key:(NSString *)key value:(NSString *)value{
    NSString *newValue = (value != nil) ? value : @"";
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSMutableArray *cookies = [NSMutableArray arrayWithArray:[cookieStorage cookiesForURL:url]];
    NSString *domian =  [url host];
    NSString *path =  [url path];
    NSMutableArray *tempCookies = [cookies copy];
    for (NSHTTPCookie *cookie in tempCookies) {
        if ([cookie.name isEqualToString:key]) {
            [cookies removeObject:cookie];
        }
    }
    NSMutableDictionary *properties = [NSMutableDictionary dictionary];
    [properties setObject:key forKey:NSHTTPCookieName];
    [properties setObject:newValue forKey:NSHTTPCookieValue];
    [properties setObject:domian forKey:NSHTTPCookieDomain];
    [properties setObject:path forKey:NSHTTPCookiePath];
    
    
    //根据NSHTTPCookie实例数组生成对应的HTTP cookie header
    //+ (NSDictionary *)requestHeaderFieldsWithCookies:(NSArray *)cookies;
    //
    //从headerFileds中读取到Cookie相关内容,生成NSHTTPCookie实例对象数组。
    //+ (NSArray *)cookiesWithResponseHeaderFields:(NSDictionary *)headerFields forURL:(NSURL *)theURL;
    //
    //该方法会忽略headerFileds中与cookie无关的字段，如果headerFileds中的cookie没有指定domain,则使用theURL的domain,如果没有指定path,则使用”/”.
    //
    //除非NSURLRequest明确指定不使用cookie(HTTPShouldHandleCookies设为NO),否则URL loading system会自动为NSURLRequest发送合适的存储cookie。从NSURLResponse返回的cookie也会根据当前的cookie访问策略(cookie acceptance policy)接收到系统中。
    
    NSHTTPCookie *cookieuser = [NSHTTPCookie cookieWithProperties:properties];
    [cookies addObject:cookieuser];
    /*The cookies will replace existing cookies with the same name, domain, and path, if one exists in the cookie storage. The cookie will be ignored if the receiver's cookie accept policy is NSHTTPCookieAcceptPolicyNever.
     To store cookies from a set of response headers, an application can use cookiesWithResponseHeaderFields:forURL: passing a header field dictionary and then use this method to store the resulting cookies in accordance with the receiver’s cookie acceptance policy.
     */
    //- (void)setCookie:(NSHTTPCookie *)aCookie
    [cookieStorage setCookies:cookies forURL:url mainDocumentURL:nil];
}
@end
